package main

import (
	//"fmt"
	"github.com/gin-gonic/gin"
	"net/http"
	"database/sql"
	_ "github.com/go-sql-driver/mysql"
	//"fmt"
	//"strconv"
)

func main() {
	router := gin.Default()
	v1 := router.Group("/api/v1/userinfo")
	{
		//v1.POST("/", CreateUser)
		v1.GET("/", FetchAllUsers)
		v1.GET("/:id", FetchSingleUser)
		//v1.PUT("/:id", UpdateUser)
		//v1.DELETE("/:id", DeleteUser)
	}
	router.Run()
}

type userinfo struct{
	Id int
	Name string
}
func FetchAllUsers(c *gin.Context){
	db, err := sql.Open("mysql", "gcore:gcore@tcp(192.168.200.248:3306)/test?charset=utf8")
	checkErr(err)

	defer db.Close()

	err = db.Ping()
	checkErr(err)

	//查询数据
	rows, err := db.Query("SELECT id,name FROM userinfo")
	checkErr(err)

	var result [...] string
	for rows.Next(){
		var userInfo userinfo
		rows.Scan(&userInfo.Id, &userInfo.Name)
		result = append(result, userInfo)
	}

	c.JSON(http.StatusOK, result)

	//var userArr [4][4]string
	//for rows.Next() {
	//	var uid int
	//	var username string
	//	var department string
	//	var created string
	//	rows.Scan(&uid, &username, &department, &created)
	//	userArr[]
	//	//checkErr(err)
	//	fmt.Println(uid)
	//	fmt.Println(username)
	//	fmt.Println(department)
	//	fmt.Println(created)
	//	ctx.JSON(http.StatusOK, [] string {strconv.Itoa(uid), username, department, created})
	//}
	//c.JSON(http.StatusOK, result)
}
func FetchSingleUser(c *gin.Context) {

	id := c.Param("id")

	db, err := sql.Open("mysql", "gcore:gcore@tcp(192.168.200.248:3306)/test?charset=utf8")
	checkErr(err)

	defer db.Close()

	err = db.Ping()
	checkErr(err)

	var (
		person Person
		result gin.H
	)
	row := db.QueryRow("select id, name from userinfo where id = ?;", id)
	err = row.Scan(&person.Id, &person.Name)
	if err != nil {
		// If no results send null
		result = gin.H{
			"result": nil,
			"count":  0,
		}
	} else {
		result = gin.H{
			"result": person,
			"count":  1,
		}
	}
	c.JSON(http.StatusOK, result)
}
func checkErr(err error) {
	if err != nil {
		panic(err)
	}
}